import { getTimes, getDate, getDay } from '../../common/common.js' 
Page({
  data: {
    userAddress: {
      address: '',
      name: ''
    },
    cameraHeight: 0,
    imgWidth: 0,
    imgHeight: 0,
    canvas: null,
    canvasCtx: null,
  },

  async onLoad(options) {
    this.getBoxHeight()
    // this.getAddress()
  },

  onReady() {
    const query = wx.createSelectorQuery()
    query.select('#canvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        const dpr = wx.getSystemInfoSync().pixelRatio
        const canvas = res[0].node
        const ctx = canvas.getContext('2d')
        canvas.width = res[0].width * dpr
        canvas.height = res[0].height * dpr
        ctx.scale(dpr, dpr)
        this.setData({ canvasCtx: ctx, canvas })
        this.drawContent()
      })
  },

  async getAddress() {
    const res = await wx.chooseLocation()
    this.setData({
      userAddress: res
    })
    this.drawAddress()
    return res
  },

  drawContent() {
    this.drawFont({
      text: getTimes(),
      x: 10,
      y: this.data.cameraHeight - 25,
      size: 35
    })
    this.drawFont({
      text: getDate(),
      x: 110,
      y: this.data.cameraHeight - 30,
      size: 13
    })
    this.drawFont({
      text: getDay(),
      x: 110,
      y: this.data.cameraHeight - 48,
      size: 12
    })
    this.drawAddress()
  },
  
  drawAddress() {
    const { address, name } = this.data.userAddress
    if (address) {
      this.drawFont({
        text: address + name,
        x: 8,
        y: this.data.cameraHeight - 10,
        size: 11
      })
    }
  },

  /**
   * 将图片等比转换成屏幕宽度
   */
  async parseImgSize(imgwidth, imgheight) {
    const { windowWidth } = await wx.getSystemInfo()
    const iheight = windowWidth * (imgheight / imgwidth)
    this.setData({
      imgWidth: windowWidth,
      imgHeight: iheight,
    })
    return {
      width: windowWidth,
      height: iheight
    }
  },

  /**
   * 绘制文字
   * @param {string} text 绘制内容 
   * @param {number} x x轴 
   * @param {number} y y轴 
   * @param {number} size 字体大小
   */
  drawFont({ text, x, y, size }) {
    this.data.canvasCtx.font = `${size}px Arial`;
    this.data.canvasCtx.fillStyle = '#fff';
    this.data.canvasCtx.textAlign = 'left'
    this.data.canvasCtx.textBaseline = 'bottom'
    this.data.canvasCtx.fillText(text, x, y)
  },

  /**
   * 获取高度
   */
  getBoxHeight() {
    const query = wx.createSelectorQuery()
    query.select('#camera-box')
      .fields({ node: true, size: true })
      .exec((res) => {
        this.setData({
          cameraHeight: res[0].height
        })
      })
  },

  /**
   * 绘制图片
   * @param {string} imgurl 图片地址 
   */
  async drawIMG(imgurl) {
    return new Promise(async (resolve, reject) => {
      var img = this.data.canvas.createImage()
      const { width, height } = await wx.getImageInfo({
        src: imgurl
      })
      const images = await this.parseImgSize(width, height)
      img.onload = () => {
        this.data.canvasCtx.drawImage(img, 0, 0, images.width, images.height)
        resolve()
      }
      img.src = imgurl
    })
  },

  async saveImages() {
   wx.showLoading({
     title: '保存中',
   })
   const {tempFilePath} = await wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: this.data.imgWidth,
      height: this.data.imgHeight,
      destWidth: this.data.imgWidth * 3,
      destHeight: this.data.imgHeight * 3,
      canvas: this.data.canvas
    })
 
    wx.saveImageToPhotosAlbum({
      filePath: tempFilePath,
      success:() => {
        wx.showToast({
          title: '成功',
          icon: 'success',
          duration: 2000
        })
        // 清空
        this.data.canvasCtx.clearRect(0, 0, this.data.imgWidth, this.data.imgHeight)
        this.drawContent()
      }
    })
  },

  takePhoto() {
    // wx.chooseImage({
    //   count: 1, //默认9	
    //   sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
    //   sourceType: ['album', 'camera'], //从相册选择
    //   success: async (res) => {
    //     await this.drawIMG(res.tempFilePaths[0])
    //     setTimeout(()=>{
    //       this.saveImages()
    //     },500)
        
    //   }
    // })
    // return
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
      quality: 'high',
      success: async (res) => {
        // this.open()
        await this.drawIMG(res.tempImagePath)
        this.drawContent()
        setTimeout(()=>{
          this.saveImages()
        }, 500)
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },
  onShareAppMessage() {
    return {
      title: '免费制作您的证件照,水印相机地点定位拍照',
      path: '/pages/home/index',
      imageUrl: '../../static/img/logon.png'
    }
  }
})